<?php

/**
 * 【后台】冲突申诉功能
 *
 * @author		maxuebing<276654894@qq.com>
 * @copyright	Copyright (c) , Chinasofti, Inc.
 */
class salesDisputeAction extends backendAction{
	
	public function __construct() {
		parent::__construct();
		
		$this->user = getUserSession();
				
	}
	
	/**
	 * 冲突申诉列表
	 */
	public function index(){
		import("ORG.Date");
		$Date = new Date(date('Y-m'));
		
		$startTime = I('startTime', date('Y-m-d', strtotime($Date->firstDayOfMonth())));
		$endTime = I('endTime', date('Y-m-d', strtotime($Date->lastDayOfMonth()) > time() ? strtotime(date('Y-m-d')) : strtotime($Date->lastDayOfMonth())));
		
		$where['d.createTime'][] = array('egt', strtotime($startTime));
		$where['d.createTime'][] = array('elt', strtotime($endTime)+(24*60*60-1));
		
		//如果是市场总监，则查找其管理地市下的销售人员
		if($this->user['roleId'] == 3){
			$where['_string'] = "cc.id = {$this->user['cityId'][0]} OR tc.id={$this->user['cityId'][0]}";
			$where['d.status'] = array('in', '3,4,5');
		}else{
			$where['_string'] = "createUserId = {$this->user['id']} OR toUserId={$this->user['id']}";
		}
		
		$field = array(
            'cu.id'=>'createUserId',
            'cu.realName'=>'createRealName',
            'tu.id'=>'toUserId',
            'tu.realName'=>'toRealName',
            'd.id',
            's.imei',
			'd.createTime',
			'm.name' => 'model',
			'b.name' => 'brand',
			'd.status',
		);
	
		$list = D("SalesDispute")->field($field)->alias("d")
				->join(C('DB_PREFIX')."admin AS cu ON cu.id = d.createUserId")
				->join(C('DB_PREFIX')."store AS cs ON cs.id = cu.storeId")
				->join(C('DB_PREFIX')."region AS cr ON cr.id = cu.regionId")
				->join(C('DB_PREFIX')."region AS cc ON cc.id = cr.pid")
				->join(C('DB_PREFIX')."admin AS tu ON tu.id = d.toUserId")
				->join(C('DB_PREFIX')."store AS ts ON ts.id = tu.storeId")
				->join(C('DB_PREFIX')."region AS tr ON tr.id = tu.regionId")
				->join(C('DB_PREFIX')."region AS tc ON tc.id = tr.pid")
				->join(C('DB_PREFIX')."sales AS s ON s.id = d.salesId")
				->join(C('DB_PREFIX')."model AS m ON m.id = s.modelId")
				->join(C('DB_PREFIX')."brand AS b ON b.id = m.brandId")
				->where($where)
				->select();

		foreach ($list as &$n){
			$n['progress'] = D('salesDispute')->getProgress($n['status'], $n['createUserId'], $n['createRealName'], $n['toUserId'], $n['toRealName']);
		}
		$where['d.createTime'][] = array('egt', strtotime($startTime));
		$where['d.createTime'][] = array('elt', strtotime($endTime)+(24*60*60-1));
		
		if($this->user['roleId'] == 7){
			//发起冲突申诉按钮
			$bigMenu = array(
					'title' =>'冲突申诉',
					'iframe' => U('salesDispute/add',array('opttype'=>'add')),
					'id' => 'add',
					'width' => '500',
					'height' => '200'         
			);
			$this->assign('big_menu',$bigMenu);
		}
		
		$this->assign('startTime', $startTime);
		$this->assign('endTime', $endTime);
		$this->assign('user', $this->user);
		$this->assign('list', $list);
		$this->display();
	}
	
	/**
	 * 发起冲突申诉
	 */
	public function _before_add(){
		if (IS_POST) {
			$imei = I('imei');

			$sales = D('Sales')->where(array('imei'=>$imei))->find();
			//找不到销量记录则提示
			if(! $sales){
				IS_AJAX && $this->ajaxReturn(0, L('can_not_find_this_imei'));
                $this->error(L('can_not_find_this_imei'));
			}
			//如果是自己录的，则提示
			if($sales['userId'] == $this->user['id']){
				IS_AJAX && $this->ajaxReturn(0, L('imei_is_yours'));
                $this->error(L('imei_is_yours'));
			}
			//如果已发起过，则提示
			$dispute = D('SalesDispute')->where(array('imei'=>$imei, 'createUserId'=>$this->user['id']))->find();
			if($dispute){
				IS_AJAX && $this->ajaxReturn(0, L('dispute_already_exists'));
                $this->error(L('dispute_already_exists'));
			}

			$_POST['salesId'] = $sales['id'];
			$_POST['createUserId'] = $this->user['id'];
			$_POST['toUserId'] = $sales['userId'];
			$_POST['createTime'] = time();
			$_POST['status'] = 0;
		}
	}
	
	/**
	 * 冲突记录详情
	 */
	public function detail(){
		$id = I('id');
		
		$field = array(
            'cu.id'=>'createUserId',
            'cu.realName'=>'createRealName',
            'cs.name'=>'createUserStoreName',
            'cc.id'=>'createUserCityId',
            'tu.id'=>'toUserId',
            'tu.realName'=>'toRealName',
            'ts.name'=>'toUserStoreName',
            'tc.id'=>'toUserCityId',
            'd.id',
            's.imei',
			's.createTime'=>'salesCreateTime',
			'd.createTime'=>'disputeCreateTime',
			'm.name' => 'model',
			'b.name' => 'brand',
			'd.status',
			'u.realName'=>'owner',	//当前IMEI所有者
		);
		$v = D("SalesDispute")->field($field)->alias("d")
			->join(C('DB_PREFIX')."admin AS cu ON cu.id = d.createUserId")
			->join(C('DB_PREFIX')."store AS cs ON cs.id = cu.storeId")
			->join(C('DB_PREFIX')."region AS cr ON cr.id = cu.regionId")
			->join(C('DB_PREFIX')."region AS cc ON cc.id = cr.pid")
			->join(C('DB_PREFIX')."admin AS tu ON tu.id = d.toUserId")
			->join(C('DB_PREFIX')."store AS ts ON ts.id = tu.storeId")
			->join(C('DB_PREFIX')."region AS tr ON tr.id = tu.regionId")
			->join(C('DB_PREFIX')."region AS tc ON tc.id = tr.pid")
			->join(C('DB_PREFIX')."sales AS s ON s.id = d.salesId")
			->join(C('DB_PREFIX')."admin AS u ON u.id = s.userId")
			->join(C('DB_PREFIX')."model AS m ON m.id = s.modelId")
			->join(C('DB_PREFIX')."brand AS b ON b.id = m.brandId")
			->where(array('d.id'=>$id))
			->find();

		// 如果当前记录是对当前登录用户发起的，且状态为0，
		if($v['toUserId'] == $this->user['id'] && $v['status'] == 0){
			$v['status'] = 1;
			
			// 则更改状态为当前登录用户已知晓
			D("SalesDispute")->where(array('id'=>$id))->save(array('status'=>1));
			//记录 imei 申诉记录更改历史
			$history['disputeId'] = $id;
			$history['userId'] = $this->user['id'];
			$history['historyStatus'] = 0;
			$history['newStatus'] = 1;
			$history['time'] = time();
			$history['content'] = '已知晓';
			D("SalesDisputeHistory")->add($history);
		}
		//处理进度
		$v['progress'] = D('salesDispute')->getProgress($v['status'], $v['createUserId'], $v['createRealName'], $v['toUserId'], $v['toRealName']);
		//状态说明
		$v['history'] = D("SalesDisputeHistory")->where(array('disputeId'=>$id, 'newStatus'=>$v['status']))->find();

		$this->assign('user', $this->user);
		$this->assign('v', $v);
		
		if (IS_AJAX) {
			$response = $this->fetch();
			$this->ajaxReturn(1, '', $response);
		} else {
			$this->display();
		}
	}
	
	
	/**
	 * 设置冲突申诉记录状态
	 */
	public function setDisputeStatus(){

		$id = I('id');
		$historyStatus = I('historyStatus');
		$newStatus  = I('newStatus');
		$content = I('content');
		
		if(! $newStatus){
			$this->ajaxReturn(0, '请选择处理结果');
		}
		
		if(empty($content) && in_array($newStatus, array(3,6,7)) == false){
			$this->ajaxReturn(0, '请填写理由');
		}
		
		$res = D('salesDispute')->setStatus($id, $historyStatus, $newStatus, $content);
		
		if($res){
			$this->ajaxReturn(1, L('operation_success'), '', 'detail');
		}else{
			$this->ajaxReturn(0, L('operation_failure'));
		}
	}
	
}

/* End of file salesDisputeAction.class.php */
